package com.example.sunmiv1.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.OtherPayListAdapter;
import com.example.sunmiv1.entity.HangOverInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.printUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HangOverActivity extends Activity {
    private String TAG=getClass().getSimpleName();
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.hangOver_people)
    TextView hangOverPeople;
    @BindView(R.id.hangOver_time)
    TextView hangOverTime;
    @BindView(R.id.hangOver_store)
    TextView hangOverStore;
    @BindView(R.id.hangOver_money)
    TextView hangOverMoney;
    @BindView(R.id.hangOver_aliPay)
    TextView hangOverAliPay;
    @BindView(R.id.hangOver_weChat)
    TextView hangOverWeChat;
    @BindView(R.id.hangOver_vip)
    TextView hangOverVip;
    @BindView(R.id.hangOver_other)
    TextView hangOverOther;
    @BindView(R.id.hangOver_moneyRecharge)
    TextView hangOverMoneyRecharge;
    @BindView(R.id.hangOver_aliRecharge)
    TextView hangOverAliRecharge;
    @BindView(R.id.hangOver_weChatRecharge)
    TextView hangOverWeChatRecharge;
    @BindView(R.id.hangOver_vipRecharge)
    TextView hangOverVipRecharge;
    @BindView(R.id.hangOver_print)
    TextView hangOverPrint;
    @BindView(R.id.hangOver_loginOut)
    TextView hangOverLoginOut;
    @BindView(R.id.handOver_sell_info_off)
    ImageView handOverSellInfoOff;
    @BindView(R.id.handOver_sell_info_cancel)
    TextView handOverSellInfoCancel;
    @BindView(R.id.handOver_sell_info_sure)
    TextView handOverSellInfoSure;
    @BindView(R.id.handOver_sell_info_lin)
    LinearLayout handOverSellInfoLin;
    @BindView(R.id.handOver_sell_other_tv)
    TextView handOverSellOtherTv;
    @BindView(R.id.handOver_sell_other_off)
    ImageView handOverSellOtherOff;
    @BindView(R.id.handOver_sell_other_list)
    ListView handOverSellOtherList;
    @BindView(R.id.handOver_sell_other_lin)
    LinearLayout handOverSellOtherLin;
    @BindView(R.id.hangOver_creditMoney)
    TextView hangOverCreditMoney;
    @BindView(R.id.hangOver_repayMoney)
    TextView hangOverRepayMoney;
    @BindView(R.id.linear_hangOver_credit)
    LinearLayout linearHangOverCredit;
    private Context context;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private HangOverInfo hangOverInfo;
    private Intent intent;
    private boolean success = false;
    private int flag = 0;//判斷是打印憑條還是交班並退出，0是打印憑條，1是交班並退出
    private boolean if_print = false;//是否打印銷售明細，false不打印，true打印
    private List<HangOverInfo.GoodsListBean> goodsList = new ArrayList<>();
    private List<HangOverInfo.PayListBean.OtherAmountArrayBean> otherPayList = new ArrayList<>();
    private OtherPayListAdapter otherPayListAdapter;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    success = true;
                    HangOverInfo.PayListBean payListBean = hangOverInfo.getPayList();
                    hangOverPeople.setText(hangOverInfo.getCashier_name());
                    hangOverTime.setText(hangOverInfo.getRecord_time());
                    hangOverStore.setText(hangOverInfo.getStore_name());
                    hangOverMoney.setText("$" + payListBean.getCash_amount());
                    hangOverAliPay.setText("$" + payListBean.getAli_amount());
                    hangOverWeChat.setText("$" + payListBean.getWeChat_amount());
                    hangOverVip.setText("$" + payListBean.getVip_amount());
                    hangOverOther.setText("$" + payListBean.getOther_amount());
                    hangOverMoneyRecharge.setText("$" + payListBean.getRecharge_cash_amount());
                    hangOverAliRecharge.setText("$" + payListBean.getRecharge_ali_amount());
                    hangOverWeChatRecharge.setText("$" + payListBean.getRecharge_weChat_amount());
                    hangOverVipRecharge.setText("$" + payListBean.getRecharge_give_amount());
                    for (HangOverInfo.GoodsListBean goodsListBean : hangOverInfo.getGoodsList()) {
                        goodsList.add(goodsListBean);
                    }
                    otherPayList.clear();
                    otherPayList.addAll(payListBean.getOther_amount_array());
                    otherPayListAdapter = new OtherPayListAdapter(otherPayList);
                    handOverSellOtherList.setAdapter(otherPayListAdapter);
                    if ("1".equals(aCache.getAsString("credit"))) {
                        hangOverCreditMoney.setText("$" + hangOverInfo.getCredit_data().getArrearage_money());
                        hangOverRepayMoney.setText("$" + hangOverInfo.getCredit_data().getRepayment_money());
                    }
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_hang_over);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.hangOverTitle);
        context = this;
        aCache = ACache.get(context);
        if ("1".equals(aCache.getAsString("credit"))) {
            linearHangOverCredit.setVisibility(View.VISIBLE);
//            hangOverCreditMoney.setVisibility(View.VISIBLE);
//            hangOverRepayMoney.setVisibility(View.VISIBLE);
        } else {
            linearHangOverCredit.setVisibility(View.GONE);
//            hangOverCreditMoney.setVisibility(View.INVISIBLE);
//            hangOverRepayMoney.setVisibility(View.INVISIBLE);
        }
        loadingDialog = new LoadingDialog(context);
        getRecord();
    }

    @OnClick({R.id.title_back, R.id.hangOver_print, R.id.hangOver_loginOut, R.id.handOver_sell_info_off,
            R.id.handOver_sell_info_cancel, R.id.handOver_sell_info_sure, R.id.handOver_sell_info_lin,
            R.id.handOver_sell_other_tv, R.id.handOver_sell_other_off, R.id.handOver_sell_other_lin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.handOver_sell_other_tv:
                handOverSellOtherLin.setVisibility(View.VISIBLE);
                break;
            case R.id.handOver_sell_other_off:
                handOverSellOtherLin.setVisibility(View.GONE);
                break;
            case R.id.handOver_sell_other_lin:
                break;
            case R.id.title_back:
                finish();
                break;
            case R.id.hangOver_print:
                if (!success) {
                    Toast.makeText(context, "請重新獲取交班信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                flag = 0;
                if (goodsList.size() > 0) {
                    if ("1".equals(aCache.getAsString("sales_diction"))) {
                        handOverSellInfoLin.setVisibility(View.VISIBLE);
                    } else {
                        wifiPrint();
                        printUtil.getInstance().printHangOver(hangOverInfo, if_print, goodsList);
                    }
                } else {
                    wifiPrint();
                    printUtil.getInstance().printHangOver(hangOverInfo, if_print, goodsList);
                }
                break;
            case R.id.hangOver_loginOut:
                if (!success) {
                    Toast.makeText(context, "請重新獲取交班信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                submitWork();
                break;
            case R.id.handOver_sell_info_off:
                handOverSellInfoLin.setVisibility(View.GONE);
                break;
            case R.id.handOver_sell_info_cancel:
                handOverSellInfoLin.setVisibility(View.GONE);
                if_print = false;
                wifiPrint();
                printUtil.getInstance().printHangOver(hangOverInfo, if_print, goodsList);
                break;
            case R.id.handOver_sell_info_sure:
                handOverSellInfoLin.setVisibility(View.GONE);
                if_print = true;
                wifiPrint();
                printUtil.getInstance().printHangOver(hangOverInfo, if_print, goodsList);
                break;
            case R.id.handOver_sell_info_lin:
                break;
        }
    }

    /*獲取交班數據*/
    private void getRecord() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.RECORD, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    hangOverInfo = GsonUtils.JsonToBean(text, HangOverInfo.class);
                    Toast.makeText(context, hangOverInfo.getMsg(), Toast.LENGTH_SHORT).show();
                    Message msg = new Message();
                    if (hangOverInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*打印憑條*/
    private void wifiPrint() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.PRINTER_RECORD_DATA, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        Log.e(TAG, "onSuccess: text="+text);
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /*交班*/
    private void submitWork() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("cashier_id", aCache.getAsString("uid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("store_id", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("merchant_id", aCache.getAsString("merchantid"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.SUBMIT_WORK, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("msg"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
//                            String login_acnum = aCache.getAsString("login_acnum");
//                            String login_pass = "";
//                            String login_ischeck = aCache.getAsString("login_ischeck");
//                            String userType = aCache.getAsString("userType");
                            String url = aCache.getAsString("url");
//                            if ("1".equals(login_ischeck)) {
//                                login_pass = aCache.getAsString("login_pass");
//                            }
                            aCache.clear();
                            aCache.put("url", url);
//                            aCache.put("login_acnum", login_acnum);
//                            aCache.put("login_pass", login_pass);
//                            aCache.put("login_ischeck", login_ischeck);
//                            aCache.put("userType", userType);
                            if (MainActivity.mainActivity != null) {
                                MainActivity.mainActivity.finish();
                            }
                            intent = new Intent(context, LoginActivity.class);
                            startActivity(intent);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
